package com.eastfair.auth.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.auth.dao.UserOrganizationMapper;
import com.eastfair.auth.entity.UserOrganization;
import com.eastfair.auth.service.UserOrganizationService;
import com.eastfair.auth.vo.UserOrganizationVo;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.businpoint.BusinLoadUserPermissPoint;
import com.eastfair.cache.auth.UserOrganizationCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.log.point.PointUtil;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.eastfair.core.exception.code.ExceptionCode.ILLEGAL_ARGUMENT_EX;

/**
 * <p>
 * 业务实现类
 *
 * </p>
 *
 * @author ligang
 * @date 2021-07-16
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class UserOrganizationServiceImpl extends SuperCacheServiceImpl<UserOrganizationMapper, UserOrganization> implements UserOrganizationService {
    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    @Autowired
    protected CacheOps cacheOps;

    @Autowired
    private PointUtil pointUtil;


    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(UserOrganization entity) {
        UpdateWrapper<UserOrganization> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(UserOrganization::getProjectId, entity.getProjectId()).eq(UserOrganization::getId, entity.getId());
        entity.setProjectId(null);
        //删除缓存
        delCache(entity);
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }

    @Override
    public List<UserOrganization> listOfUserOrganization(UserOrganization userOrganization, List<Long> userIds, List<Long> orgIds) {
        //查询
        QueryWrapper<UserOrganization> queryWrapper = new QueryWrapper<>();
        if (userOrganization != null) {
            if (userOrganization.getId() != null) {
                queryWrapper.lambda().eq(UserOrganization::getId, userOrganization.getId());
            }
            if (userOrganization.getUserId() != null) {
                queryWrapper.lambda().eq(UserOrganization::getUserId, userOrganization.getUserId());
            }
            if (userOrganization.getOrganizationId() != null) {
                queryWrapper.lambda().eq(UserOrganization::getOrganizationId, userOrganization.getOrganizationId());
            }
        }
        if (userOrganization != null && userOrganization.getProjectId() != null) {
            queryWrapper.lambda().eq(UserOrganization::getProjectId, userOrganization.getProjectId());
        } else if (ContextUtil.getProjectId() != null) {
            queryWrapper.lambda().eq(UserOrganization::getProjectId, ContextUtil.getProjectId());
        }


        if (userIds != null && !userIds.isEmpty()) {
            queryWrapper.lambda().in(UserOrganization::getUserId, userIds);
        }
        if (orgIds != null && !orgIds.isEmpty()) {
            queryWrapper.lambda().in(UserOrganization::getOrganizationId, orgIds);
        }
        queryWrapper.lambda().eq(UserOrganization::getIsDeleted, BusinessConstant.DELETE_NO);
        List<UserOrganization> organizationList = list(queryWrapper);
        return organizationList;
    }

    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new UserOrganizationCacheKeyBuilder();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(UserOrganization model) {
        //雪花ID
        model.setId(DefaultUidGenerator.getUidOfProjectId(model.getProjectId()));
        return R.successDef();
    }


    @Override
    public R del(Long id, Long projectId) {
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setId(id);
        userOrganization.setIsDeleted(BusinessConstant.DELETE_YES);
        userOrganization.setProjectId(projectId);
        updateByIdOfShard(userOrganization);
        return R.successDef();
    }

    @Override
    public R delOfOrgIds(List<Long> orgIds) {
        List<UserOrganization> userOrganizationList = listOfUserOrganization(null, null, orgIds);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            for (UserOrganization userOrganization : userOrganizationList) {
                userOrganization.setIsDeleted(BusinessConstant.DELETE_YES);
                updateByIdOfShard(userOrganization);
            }
        }
        return R.successDef();
    }

    @Override
    public List<UserOrganization> queryUserByOrg(List<Long> orgIds) {
        return listOfUserOrganization(null, null, orgIds);
    }

    @Override
    public List<UserOrganizationVo> queryUserVoByOrg(List<Long> orgIds) {
        return doToVos(queryUserByOrg(orgIds));
    }


    @Override
    public R<UserOrganization> addUserOfOrg(Long orgId, List<Long> userIds, Long projectId) {
        if (orgId == null || userIds == null || userIds.isEmpty()) {
            return R.fail(ILLEGAL_ARGUMENT_EX);
        }
        //剔除已经添加的用户
        UserOrganization query = new UserOrganization();
        query.setOrganizationId(orgId);
        List<UserOrganization> userOrganizationList = listOfUserOrganization(query, userIds, null);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            for (UserOrganization userOrganization : userOrganizationList) {
                userIds.remove(userOrganization.getUserId());
            }
        }
        //添加
        if (userIds != null && !userIds.isEmpty()) {
            for (Long userId : userIds) {
                UserOrganization userOrganization = new UserOrganization();
                userOrganization.setOrganizationId(orgId);
                userOrganization.setUserId(userId);
                userOrganization.setProjectId(projectId);
                save(userOrganization);
                return R.success(userOrganization);
            }
        }
        //添加到事件监听队列
        BusinLoadUserPermissPoint businLoadUserPermissPoint = new BusinLoadUserPermissPoint();
        businLoadUserPermissPoint.setUserIdList(userIds);
        businLoadUserPermissPoint.setProjectId(ContextUtil.getProjectId());
        pointUtil.addBusinPointMsg(businLoadUserPermissPoint);
        return R.fail("添加失败");
    }


    @Override
    public R removeUserOfOrg(Long orgId, List<Long> removeUserIds) {
        if (orgId == null || removeUserIds == null || removeUserIds.isEmpty()) {
            return R.fail(ILLEGAL_ARGUMENT_EX);
        }
        //剔除已经添加的用户
        UserOrganization query = new UserOrganization();
        query.setOrganizationId(orgId);
        List<UserOrganization> userOrganizationList = listOfUserOrganization(query, removeUserIds, null);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            for (UserOrganization userOrganization : userOrganizationList) {
                userOrganization.setIsDeleted(BusinessConstant.DELETE_YES);
                updateByIdOfShard(userOrganization);
            }
        }

        //添加到事件监听队列
        BusinLoadUserPermissPoint businLoadUserPermissPoint = new BusinLoadUserPermissPoint();
        businLoadUserPermissPoint.setUserIdList(removeUserIds);
        businLoadUserPermissPoint.setProjectId(ContextUtil.getProjectId());
        pointUtil.addBusinPointMsg(businLoadUserPermissPoint);
        return R.success();
    }

    @Override
    public R removeUserOfOrg(List<Long> orgIds, List<Long> removeUserIds) {
        if (orgIds == null || orgIds.isEmpty() || removeUserIds == null || removeUserIds.isEmpty()) {
            return R.fail(ILLEGAL_ARGUMENT_EX);
        }
        //剔除已经添加的用户
        List<UserOrganization> userOrganizationList = listOfUserOrganization(null, removeUserIds, orgIds);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            for (UserOrganization userOrganization : userOrganizationList) {
                userOrganization.setIsDeleted(BusinessConstant.DELETE_YES);
                updateByIdOfShard(userOrganization);
            }
        }

        //添加到事件监听队列
        BusinLoadUserPermissPoint businLoadUserPermissPoint = new BusinLoadUserPermissPoint();
        businLoadUserPermissPoint.setUserIdList(removeUserIds);
        businLoadUserPermissPoint.setProjectId(ContextUtil.getProjectId());
        pointUtil.addBusinPointMsg(businLoadUserPermissPoint);
        return R.success();
    }


    public UserOrganizationVo doToVo(UserOrganization userOrganization) {
        UserOrganizationVo userOrganizationVo = new UserOrganizationVo();
        BeanUtils.copyProperties(userOrganization, userOrganizationVo);
        userOrganizationVo.setId(userOrganization.getId());
        return userOrganizationVo;
    }

    public List<UserOrganizationVo> doToVos(List<UserOrganization> userOrganizationList) {
        if (userOrganizationList == null || userOrganizationList.isEmpty()) {
            return null;
        }
        List<UserOrganizationVo> result = new ArrayList<>();
        for (UserOrganization userOrganization : userOrganizationList) {
            result.add(doToVo(userOrganization));
        }
        return result;
    }


}
